import { BooleanResult } from '@/data/result';
import { add, remove, submit, update } from '@/services/data';
import { message } from 'antd';

export const handleAdd = async (url: string, params: any) => {
  const hide = message.loading('正在添加');

  const { data, code, msg, success }: BooleanResult = await add(url, params);
  hide();
  if (success) {
    message.success('添加成功');
    return data;
  } else {
    message.error(`添加失败,错误码${code}：${msg}`);
    return;
  }
};

export const handleUpdate = async (url: string, fields: any, currentRow?: any) => {
  const hide = message.loading('正在更新');

  const { data, code, msg, success }: BooleanResult = await update(url, {
    ...currentRow,
    ...fields,
  });
  hide();
  if (success) {
    message.success('更新成功');
    return data;
  } else {
    message.error(`更新失败,错误码${code}：${msg}`);
    return;
  }
};

export const handleRemove = async (url: string, id: string) => {
  const hide = message.loading('正在删除');

  const { data, code, msg, success }: BooleanResult = await remove(url, id);
  hide();
  if (success) {
    message.success('删除成功，即将刷新');
    return data;
  } else {
    message.error(`删除失败,错误码${code}：${msg}`);
    return;
  }
};
export const handleRemoveList = async (url: string, selectedRows: any) => {
  const hide = message.loading('正在删除');
  if (!selectedRows) return true;

  selectedRows.map(async (row: any) => await remove(url, row.id));
  hide();
  message.success('删除完成，即将刷新');
  return true;
};

export const handleSubmit = async (url: string, params: any) => {
  const hide = message.loading('正在提交');

  const { data, code, msg, success }: any = await submit(url, params);
  hide();
  if (success) {
    message.success('提交成功，即将刷新');
    return data;
  } else {
    message.error(`提交失败,错误码${code}：${msg}`);
    return;
  }
};
